import datetime

import jwt
from django.contrib.auth.hashers import check_password
from django.core.mail import send_mail
from rest_framework.views import APIView
from rest_framework.response import Response

from HYDDjango.settings import EMAIL_HOST_USER, SECRET_KEY
from .sers import RegisterSerializer
from .models import *

class RegisterView(APIView):
    def post(self,request):
        #创建序列化器  传入数据
        ser = RegisterSerializer(data=request.data)

        #验证数据
        if ser.is_valid():
            #保存并返回
            ser.save()

            #发送一个激活邮件，让用户去激活
            send_mail(subject="激活邮件",message="已激活",from_email=EMAIL_HOST_USER,
                      recipient_list=[request.data.get("email")],html_message="恭喜你注册成功，请领取奖励<a href='http://127.0.0.1:8000/user/active/'>查收</a>！<a href='http://127.0.0.1:8000/user/login/'>跳到vue</a>")

            return Response({"msg": "注册成功", "status": 200})
        else:
            print(ser.errors)
            return Response({"msg": "注册失败", "status": 400, "error": ser.errors})


class UserView(APIView):
    def get(self,request):
        #获取 传递来的 用户名
        username = request.GET.get("username")

        #数据库查询是否存在
        if User.objects.filter(username=username):
            return Response({"msg": "该用户名已使用", "status": 400})

        return Response({"msg": "用户名可用", "status": 200})


def active_user(request):
    # 激活的本意 就是 修改用户的状态
    id = request.GET.get("id")
    User.objects.filter(id=id).update(level=2)
    return Response({"msg": "激活成功"})

class LoginView(APIView):

    def post(self, request):
        username = request.data.get("username")
        password = request.data.get("password")

        # 验证
        user = User.objects.filter(username=username).first()

        print("user.password=", user.password)

        if user and check_password(password, user.password):
            # 登录成功 生成一个令牌
            payload = {
                # exp 表示到期时间
                'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=1),
                'data': {  # 自定义 个人存放信息
                    'uid': user.id
                }
            }
            key = jwt.encode(payload, SECRET_KEY)
            return Response({"msg": "登录成功", "status": 200, "token": key})

        return Response({"msg": "登录失败", "status": 400})


class TestTokenView(APIView):

    def get(self, request):
        token = request.GET.get("token")
        print(token)

        # 验证 令牌
        data = jwt.decode(token, SECRET_KEY, verify=True)
        print(data)
        uid = data.get("data").get("uid")
        print("uid:", uid)
        user = User.objects.get(id=uid)

        return Response({"msg": "%s 已经登录了" % user.username})

    def post(self, request):
        return Response({"msg": "添加成功"})